package com.client.ble

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.base.callback.BleScanCallback
import com.base.event.BleEvent
import com.base.event.observe.observeEvent
import com.base.receiver.BleScanDeviceReceiver
import com.base.util.BleManager
import com.base.util.dialog
import com.base.util.log
import com.client.ble.adapter.BleAdapter
import com.client.ble.databinding.ActivitySplashBinding
import java.lang.Exception

class SplashActivity : AppCompatActivity() {
    private val bleAdapter by lazy { BleAdapter(this) }
    private val binding by lazy { ActivitySplashBinding.inflate(layoutInflater) }
    private lateinit var permissionResultLauncher: ActivityResultLauncher<Array<String>>
    private var btReceiver: BleScanDeviceReceiver? = null

    private val _arrayLocation = arrayOf(
        android.Manifest.permission.ACCESS_FINE_LOCATION,
        android.Manifest.permission.ACCESS_COARSE_LOCATION
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.listView.apply {
            adapter = bleAdapter
        }
        permissionResultLauncher =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
                if (it.values.contains(false)) {
                    dialog("未授权!")
                    binding.bleSwitch.isChecked = false
                    return@registerForActivityResult
                }
                openBle()
            }

        val supportBle = BleManager.getInstance().supportBle()
        if (!supportBle) {
            binding.bleSwitch.visibility = View.GONE
            Log.e("onCreate: ", "当前设备不支持蓝牙功能")
        }
        BleManager.getInstance().bleOpened().observe(this, {
            binding.bleSwitch.isChecked = it
        })
        observeEvent<BleEvent> { it ->
            binding.bleSwitch.isChecked = it.opened
            if (it.opened)
                binding.bleScan.visibility = View.VISIBLE
            it.deviceList.forEach { device ->
                log(
                    message = "\nname is->${device.name}" +
                            "\naddress is->${device.address}" +
                            "\nbondState is->${device.bondState}" +
                            "\ntype is->${device.type}"
                )
            }
        }
        binding.bleSwitch.setOnClickListener { checkLocationPermission() }
        binding.bleSwitch.setOnCheckedChangeListener(null)
        binding.bleScan.setOnClickListener { BleManager.getInstance().startDiscovery() }
        checkLocationPermission()
    }

    private fun checkLocationPermission() {
        val definePermission = _arrayLocation.filter {
            val code = ContextCompat.checkSelfPermission(this, it)
            PackageManager.PERMISSION_GRANTED != code
        }.toTypedArray()
        if (definePermission.isNotEmpty()) {
            binding.bleSwitch.isChecked = false
            permissionResultLauncher.launch(definePermission)
        } else {
            binding.bleSwitch.setOnClickListener(null)
            binding.bleSwitch.setOnCheckedChangeListener { _, isChecked ->
                /*val manager = BleManager.getInstance()
                if (isChecked)
                    manager.open()
                else
                    manager.close()*/
            }
            openBle()
        }
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        btReceiver = BleScanDeviceReceiver(object : BleScanCallback {
            override fun onDeviceFound(device: BluetoothDevice) {
                runOnUiThread {
                    if (device.bondState != BluetoothDevice.BOND_BONDED) {
                        val devices = "${device.name}\n${device.address}".trimIndent()
                        Log.e("onDeviceFound: ", "devices=$devices")
                        /*if (!btFoundList.contains(devices)) {
                            btFoundList.add(devices)
                            try {
                                btFoundAdapter.notifyDataSetChanged()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }*/
                    }
                }
            }

            override fun onScanFinished() {
                runOnUiThread {
                    /*val noDevices = getString(R.string.none_ble_device)
                    if (btFoundList.isEmpty()) {
                        btFoundList.add(noDevices)
                        try {
                            btFoundAdapter.notifyDataSetChanged()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }*/
                }
            }
        })
        //注册蓝牙广播接收者
        //注册蓝牙广播接收者
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        registerReceiver(btReceiver, intentFilter)
    }

    //申请打开蓝牙
    private fun openBle() {
        //BleManager.getInstance().open()
        //BleManager.getInstance().open(this)
        startActivity(Intent(this, ChatActivity::class.java))
    }

    override fun finish() {
        btReceiver?.let { unregisterReceiver(it) }
        super.finish()
    }
}